package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constant.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Transactional
@Service
@Slf4j
@EnableScheduling //开启定时任务
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 0/1 * * * ? ") //每分钟刷新一次
    public void refresh() {
        //分布式锁
        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 2);
        if (StringUtils.isNotBlank(token)) {
            log.info("未来数据定时刷新:{}", new Date());
            //获取未来数据集合key值
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];
                Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                if (tasks != null && !tasks.isEmpty()) {
                    cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                    log.info("成功将" + futureKey + "刷新到了" + topicKey);
                }
            }
        }
    }


    /**
     * 数据库同步到redis
     */
    @Override
    @PostConstruct //初始化方法,微服务启动后就会调用该方法
    @Scheduled(cron = "0 0/5 * * * ?")
    public void reloadData() {
        log.info("数据同步到redis");
        //清理redis缓存
        log.info("【清理redis缓存】");
        clearChche();
        //查看小于未来五分钟的所有任务
        log.info("【同步未来五分钟任务】");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime()));
        for (Taskinfo taskinfo : taskinfos) {
            Task task = new Task();
            BeanUtils.copyProperties(taskinfo, task);
            taskinfo.setExecuteTime(taskinfo.getExecuteTime());
            addTaskToCache(task);
        }

    }

    /**
     * 清理redis缓存
     */
    private void clearChche() {
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(futureKeys);
        cacheService.delete(topicKeys);
    }

    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        log.info("【延迟任务-消费任务】");
        Task task = null;
        try{
            String key  = type + "_" + priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if(StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("poll task error");
        }
        return task;
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public boolean cancelTask(Long taskId) {
        log.info("【延迟任务-取消任务】taskId:{}",taskId);
        boolean flag = false;
        //删除任务，更新日志
        log.info("【db:删除任务，更新日志】");
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);
        //删除redis中数据
        if(task != null){
            log.info("【redis:删除任务】");
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType()+"_"+task.getPriority();

        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key, JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志状态
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(Long taskId, int status) {
        Task task = null;
        try {
            //删除mysql中taskinfo
            taskinfoMapper.deleteById(taskId);
            //更新taskinfoLogs
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            //返回task

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());

        }catch (Exception e){
            log.error("task cancel exception taskid={}",taskId);
        }
        return task;
    }

    /**
     * 添加任务
     * @param task
     * @return
     */
    @Override
    public long addTask(Task task) {

        //1.任务存到数据库中
        log.info("【延迟任务-添加任务】task:{}", JSON.toJSONString(task));
        log.info("将任务添加到mysql中");
        boolean success = addTaskToDb(task);
        //2.添加任务到redis中
        //2.1如果任务的执行时间小于当前时间，放入list
        //2.2xx 大于当前时间 && 小于未来五分钟,放入zset中
        if (success) {
            log.info("将任务添加到redis中");
            addTaskToCache(task);
        }

        return task.getTaskId();
    }

    /**
     * 添加任务到redis
     * @param task
     */
    private void addTaskToCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();
        //获取5分钟之后的时间 毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5); //
        long nextScheduleTime = calendar.getTimeInMillis();
        if(task.getExecuteTime() <= System.currentTimeMillis()){
            //存入list中
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
        }else if(task.getExecuteTime() <= nextScheduleTime){
            //存入zset中
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    /**
     * 任务存入db中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try{
            //1.保存任务表
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //2.设置任务id
            Long taskId = taskinfo.getTaskId();
            task.setTaskId(taskId);
            //3.保存日志信息
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setTaskId(taskId);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return flag;
    }
}
